package com.shaoshaohuo.app.ui.shipper;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.CarListAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.ListViewAction;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.Car;
import com.shaoshaohuo.app.entity.CarListEntity;
import com.shaoshaohuo.app.entity.SearchCar;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.SearchCarActivity;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.XListView;
import com.shaoshaohuo.app.view.XListView.IXListViewListener;

import java.util.ArrayList;
import java.util.List;

public class FindCarActivity extends BaseActivity implements IXListViewListener, OnClickListener {

    public static final int SEARCH = 50;

    private TopbarView mTopbarView;
    private XListView mCargoListview;
    private TextView tv_search;
    private RelativeLayout rl_search;
    private TextView tv_send_ad;
    private TextView tv_end_ad;
    private TextView tv_search_detail;
    private ImageView iv_cancel;

    private CarListAdapter<Car> mAdapter;

    private List<Car> mDataList = new ArrayList<Car>();
    private int size = 10;
    private String action = ListViewAction.NEW;
    private String cursor = "0";
    private String lng = "";
    private String lat = "";
    private SearchCar searchCar = new SearchCar();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_car);
        lng = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.LNG, "");
        lat = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.LAT, "");

        initView();
        setUpView();
        searchCar(true);
    }

    private void initView() {
        mTopbarView = (TopbarView) this.findViewById(R.id.topbar);
        mCargoListview = (XListView) this.findViewById(R.id.listview_cargo_list);

        tv_search = (TextView) findViewById(R.id.tv_search);
        rl_search = (RelativeLayout) findViewById(R.id.rl_search);
        tv_send_ad = (TextView) findViewById(R.id.tv_send_ad);
        tv_end_ad = (TextView) findViewById(R.id.tv_end_ad);
        tv_search_detail = (TextView) findViewById(R.id.tv_search_detail);
        iv_cancel = (ImageView) findViewById(R.id.iv_cancel);
    }

    private void setUpView() {
        mTopbarView.setCenterText("我要找车");
        mTopbarView.setLeftView(true, true);
        mCargoListview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Car item = (Car) parent.getItemAtPosition(position);
                Intent intent = new Intent(FindCarActivity.this, CarOwnerInfoActivity.class);
                intent.putExtra(ExtraName.caruserid, item.getCaruserid());
                startActivity(intent);
            }
        });
        setListView();

        iv_cancel.setOnClickListener(this);
        tv_search.setOnClickListener(this);
        rl_search.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_cancel:
                searchCar  = new SearchCar();
                rl_search.setVisibility(View.GONE);
                tv_search.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_search:
            case R.id.rl_search:
                Intent intent = new Intent(this, SearchCarActivity.class);
                intent.putExtra(ExtraName.searchCar, searchCar);
                startActivityForResult(intent, SEARCH);
                break;
        }
    }


    private void searchCar(boolean isLoading) {
        if (isLoading) {
            startLoadingDialog();
        }

//        initLocation();
//		Log.e("choose", "action :" + action + "size:" + size + "cursor :" + cursor + "lng :" + lng + "lat:" + lat + "cartype:" + cartype + "carcid:" + carcid + "longoption:" + longoption + "weightoption:" + weightoption + "origincityid:" + origincityid + "receivecityid:" + receivecityid);

        RequestService.getInstance().searchCar(this, action, size + "", cursor, lng, lat,
                searchCar.cartype, searchCar.carcid, searchCar.longoption == 0 ? "" : searchCar.longoption + "", searchCar.weightoption == 0 ? "" : searchCar.weightoption + "",
                searchCar.origincityid, searchCar.receivecityid, searchCar.triptype, CarListEntity.class, new RequestListener() {
                    @Override
                    public void onSuccess(int requestCode, BaseEntity resultData) {
                        dismissLoadingDialog();
                        if (resultData.isOk()) {
                            CarListEntity entity = (CarListEntity) resultData;
                            List<Car> list = entity.getData().getList();
                            mDataList.addAll(list);
                            if ((mDataList.size() < size) || (action.equals(ListViewAction.HISTORY) && list.size() < size)) {
                                mCargoListview.endLoadingMore("没有更多了");
                            }
                            setAdapter(mDataList);
                        } else {
                            showToast(resultData.getMsg());
                        }
                        onLoad();
                    }

                    @Override
                    public void onFailed(int requestCode, Exception error, String msg) {
                        dismissLoadingDialog();
                        showToast(R.string.please_check_network);
                        onLoad();
                    }
                });
    }


    protected void setAdapter(List<Car> mDataList2) {

        if (mAdapter == null) {
            mAdapter = new CarListAdapter<Car>(this, mDataList2, false, lat, lng);
            mCargoListview.setAdapter(mAdapter);
        } else {
            mAdapter.setData(mDataList2);
        }
    }

    private void setListView() {
        mCargoListview.setPullLoadEnable(true);
        mCargoListview.setPullRefreshEnable(true);
        mCargoListview.setXListViewListener(this);
    }

    @Override
    public void onRefresh() {
        cursor = "0";
        mDataList.clear();
        action = ListViewAction.NEW;
        mCargoListview.setPullLoadEnable(true);
        searchCar(false);
    }

    @Override
    public void onLoadMore() {
        if (mDataList.size() > 0) {
            cursor = mDataList.get(mDataList.size() - 1).getCursor();
        } else {
            cursor = "0";
        }
        action = ListViewAction.HISTORY;
        searchCar(false);
    }

    private void onLoad() {
        mCargoListview.stopRefresh();
        mCargoListview.stopLoadMore();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SEARCH) {
                searchFinish(data);
            }
        }
    }

    private void searchFinish(Intent data) {
        searchCar = (SearchCar) data.getSerializableExtra(ExtraName.searchCar);
        onRefresh();
        if (TextUtils.isEmpty(searchCar.origincityid)) {
            tv_send_ad.setText("全国");
        } else {
            tv_send_ad.setText(searchCar.originName);
        }
        if (TextUtils.isEmpty(searchCar.receivecityid)) {
            tv_end_ad.setText("全国");
        }else{
            tv_end_ad.setText(searchCar.receiveName);
        }

        StringBuilder stringBuilder = new StringBuilder();
        if (!TextUtils.isEmpty(searchCar.carName)) {
            stringBuilder.append(searchCar.carName+",");
        }
        if (!TextUtils.isEmpty(searchCar.longName)) {
            stringBuilder.append(searchCar.longName+",");
        }
        if (!TextUtils.isEmpty(searchCar.weightName)) {
            stringBuilder.append(searchCar.weightName+",");
        }
        if ("2".equals(searchCar.triptype)) {
            stringBuilder.append("回程车");
        }else{
            stringBuilder.append("直发车");
        }
        String str = stringBuilder.toString();
        if (str.endsWith(",")) {
            str.substring(0, str.length() - 1);
        }
        tv_search_detail.setText(str);
        tv_search.setVisibility(View.GONE);
        rl_search.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
